package com.yz.jdd.module.upgrade;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.trello.rxlifecycle.ActivityEvent;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.launch.model.AppVersion;
import com.yz.jdd.module.login.view.LoginActivity;
import com.yz.jdd.module.main.MainActivity;
import com.yz.jdd.webview.download.H5DownFileUtils;

import java.io.File;

import rx.functions.Action1;

public class DownLoadDialogActivity extends BaseActivity {

    private TextView title;
    private TextView content;
    private Button ok;
    private Button cancel;
    private ProgressBar progressBar;
    private TextView downLoadSize;
    private TextView  versionCode;
    //下载数据
    private AppVersion appVersion;
    private String apkUrl;
    private String autoLogin;
    private boolean isforceUpgrade;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);
        appVersion = (AppVersion) getIntent().getSerializableExtra("appVersion");
        versionCode=findViewById(R.id.versionCode);
        apkUrl = getIntent().getStringExtra("url");
        autoLogin = getIntent().getStringExtra("autoLogin");
        if (appVersion != null) {
            showVersionUpdate();
        } else {
            finish();
        }
        //注册监听接收下载进度
        RxBus.with(this).setEvent(Events.EVENT_DOWNLOAD_PROGRESS).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                int count = events.getContent();
                if (count == 1001) {
                    showProgressDialog("下载失败请重试", "", "重新下载");
                    if (progressBar != null && downLoadSize != null) {
                        progressBar.setVisibility(View.GONE);
                        downLoadSize.setVisibility(View.GONE);
                    }
                } else if (count == 1002) {
                    setMessage("下载完成,请立即安装!");
                    ok.setText("立即安装");
                    ok.setVisibility(View.VISIBLE);
                    ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String downloadPath;
                            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                                downloadPath = Environment.getExternalStorageDirectory()
                                        .getPath();
                            } else {
                                downloadPath = getFilesDir().getAbsolutePath();
                            }
                            File file = new File(downloadPath);
                            if (file.exists()) {
                                file.delete();
                            }
                            file.mkdir();
                            File fileApk = new File(downloadPath + File.separator + "temp.apk");
                            Intent intent = new Intent();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setAction(Intent.ACTION_VIEW);
                            String type = "application/vnd.android.package-archive";
                            intent.setDataAndType(Uri.fromFile(fileApk), type);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                Uri contentUri = FileProvider.getUriForFile(DownLoadDialogActivity.this, "com.yz.jdd.provider", fileApk);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                            } else {
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive");
                            }
                            //不再显示GuideActivity
                            PreferencesUtils.putBoolean(MyApplication.application, Constants.PRE_SHOW_GUIDE, true);
                            startActivity(intent);

                        }
                    });
                } else {
                    if (progressBar != null) {
                        progressBar.setProgress(count);
                        downLoadSize.setText(count + "%");
                    }
                }
            }
        }).create();

    }

    public void showVersionUpdate() {
        // 强制升级
        isforceUpgrade = "true".equals(appVersion.getForceUpdate());
        String desc = appVersion.getDescription();
        String versionCodeStr=appVersion.getVersion();
        versionCode.setText(versionCodeStr+"");
        desc = desc.replace("|", "\n");
        setTitle("商家APP更新啦");
        setMessage(desc);
        setRightBtn("立即升级",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("立即升级".equals(ok.getText())) {
                            //开始下载
                            Intent intent = new Intent(
                                    DownLoadDialogActivity.this,
                                    NewAPKDownLoaderService.class);
                            intent.putExtra("url", apkUrl);
                            startService(intent);
//                            clearVersionStatus();
                            if (isforceUpgrade) {
                                showProgressDialog("", "正在下载最新版本安装包，请稍候……", "");
                            } else {
                                showProgressDialog("", "正在下载最新版本安装包，请稍候……", "后台下载");
                            }
                        }
                    }
                });
        if (!isforceUpgrade) {
            //非强升
            setLeftBtn("稍后再说",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //记录一下时间
                            PreferencesUtils.putLong(DownLoadDialogActivity.this, BaseConfigs.LONG_TIMESTAP, System.currentTimeMillis());
                            if ("H5Bridge".equals(autoLogin)) {

                            } else if ("true".equals(autoLogin)) {
                                startMainActivity();
                            } else {
                                startLoginActivity();
                            }
                            finish();
                        }
                    });
        }
    }

    private void showProgressDialog(String title, String msg, final String btnRightValue) {
        getProgressBar();
        getTextSize();
        setTitle(title);
        setMessage(msg);
        setMessageGravityLeft();
        findViewById(R.id.btn_divider).setVisibility(View.GONE);
        findViewById(R.id.btn_cancel).setVisibility(View.GONE);
        setRightBtn(btnRightValue, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("后台下载".equals(ok.getText())) {
                    if ("H5Bridge".equals(autoLogin)) {

                    } else if ("true".equals(autoLogin)) {
                        startMainActivity();
                    } else {
                        startLoginActivity();
                    }
                    finish();
                } else if ("重新下载".equals(ok.getText())) {
                    //开始下载
                    Intent intent = new Intent(
                            DownLoadDialogActivity.this,
                            NewAPKDownLoaderService.class);
                    intent.putExtra("url", apkUrl);
                    startService(intent);
                    if (isforceUpgrade) {
                        showProgressDialog("", "正在下载最新版本安装包，请稍候……", "");
                    } else {
                        showProgressDialog("", "正在下载最新版本安装包，请稍候……", "后台下载");
                    }
                }
            }
        });
        if ("下载失败请重试".equals(title)) {
            setLeftBtn("其他方式", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openBrowser(DownLoadDialogActivity.this, apkUrl);
                }
            });
        }
    }

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }


    public ProgressBar getProgressBar() {
        progressBar = (ProgressBar) findViewById(R.id.progress_horizontal);
        progressBar.setVisibility(View.VISIBLE);
        return progressBar;
    }

    public TextView getTextSize() {
        downLoadSize = (TextView) findViewById(R.id.size);
        downLoadSize.setVisibility(View.VISIBLE);
        return downLoadSize;
    }

    public void setTitle(String stitle) {
        title = (TextView) findViewById(R.id.title);
        if (!TextUtils.isEmpty(stitle)) {
            title.setVisibility(View.VISIBLE);
            title.setText(stitle);
        } else {
            title.setVisibility(View.GONE);
        }
    }

    public void setMessage(String msg) {
        content = (TextView) findViewById(R.id.content);
        if (TextUtils.isEmpty(msg)) {
            content.setVisibility(View.GONE);
        } else {
            content.setVisibility(View.VISIBLE);
            content.setText(msg);
        }
    }

    public void setMessageGravityLeft() {
        if (content != null) {
            content.setGravity(Gravity.LEFT);
        }
    }


    public void setRightBtn(String strOK, View.OnClickListener listener) {
        if (!TextUtils.isEmpty(strOK)) {
            ok = (Button) findViewById(R.id.btn_ok);
            ok.setText(strOK);
            ok.setVisibility(View.VISIBLE);
            ok.setOnClickListener(listener);
        } else {
            ok.setVisibility(View.GONE);
        }
    }


    public void setLeftBtn(String strRight, View.OnClickListener listener) {
        if (!TextUtils.isEmpty(strRight)) {
            View btn_divider = findViewById(R.id.btn_divider);
            btn_divider.setVisibility(View.VISIBLE);
            cancel = (Button) findViewById(R.id.btn_cancel);
            cancel.setText(strRight);
            cancel.setVisibility(View.VISIBLE);
            cancel.setOnClickListener(listener);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (ok.getText().equals("立即安装")) {
                if ("H5Bridge".equals(autoLogin)) {
                    finish();
                } else {
                    if (!isforceUpgrade) {
                        if ("true".equals(autoLogin)) {
                            startMainActivity();
                        } else {
                            startLoginActivity();
                        }
                    }
                 //   finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    public void clearVersionStatus() {
//        //初始化安装补丁错误次数文件
//
//        String currentVersion = "";
//        try {
//            ApplicationLike applicationLike = TinkerManager
//                    .getTinkerApplicationLike();
//            currentVersion = TinkerApplicationHelper
//                    .getCurrentVersion(applicationLike);
//        } catch (Exception e) {
//            currentVersion = "";
//        }
//
//        SharedPreferences sp = MyApplication.application
//                .getSharedPreferences(
//                        ShareConstants.TINKER_SHARE_PREFERENCE_CONFIG,
//                        Context.MODE_MULTI_PROCESS);
//        SharedPreferences.Editor editor = sp.edit();
//        editor.putInt(currentVersion, 0);
//        editor.putInt("composeFailCount", 0);
//        editor.commit();
//    }

    public void startMainActivity() {
        Intent intent = new Intent(DownLoadDialogActivity.this, MainActivity.class);
        String main_url = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + "vuepages/index.html#/?s=" +
                PreferencesUtils.getString(this, BaseConfigs.PREF_SESSIONID) +
                "&statusBarHeight=0&android=4.1" + "&SDK=" + Build.VERSION.SDK_INT
                + "&url=" + PreferencesUtils.getString(DownLoadDialogActivity.this, BaseConfigs.STRING_SERVER_URL, Constants.SERVER_URL);
        intent.putExtra(Constants.H5_WEB_URL, main_url);
        startActivity(intent);
    }

    public void startLoginActivity() {
//        int appCode = AppUtils.getVerCode(DownLoadDialogActivity.this);
//        int saveCode = PreferencesUtils.getInt(this, BaseConfigs.INT_APP_VERSION,
//                -1);
//        if (appCode == saveCode) {
//            Intent intent = new Intent(DownLoadDialogActivity.this, LoginActivity.class);
//            startActivity(intent);
//        } else {
//            Intent intent = new Intent(DownLoadDialogActivity.this, WelcomActivity.class);
//            startActivity(intent);
//        }
        Intent intent = new Intent(DownLoadDialogActivity.this, LoginActivity.class);
        startActivity(intent);
    }
}
